package com.lagou.edu.controller;


import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.LagouAuthCodeService;
import com.lagou.edu.utils.FormatVaildate;
import com.lagou.edu.utils.MyDateTime;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;

@RequestMapping("/api/code")
@RestController
public class CodeController {

    @Reference
    private LagouAuthCodeService lagouAuthCodeService;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 校验验证码是否正确，0正确1错误2超时
     * @param email
     * @param code
     * @return
     */
    @RequestMapping("/vaildate/{email}/{code}")
    public Integer vaildate(@PathVariable("email") String email,@PathVariable("code") String code) throws ParseException {
        if (StringUtils.isEmpty(code)){
            return 1;
        }
        LagouAuthCode rs = lagouAuthCodeService.getByEmailAndCode(email, code);
        if (rs != null && rs.getId() != null){
            return MyDateTime.dateToStamp(rs.getExpiretime()) - System.currentTimeMillis() <= 0 ? 2 : 0;
        }
        return 1;
    }
    /**
     * 发送验证码到邮箱,true成功,false失败
     * @param email
     * @return
     */
    @RequestMapping("/create/{email}")
    public Boolean create(@PathVariable("email") String email){
        if (!FormatVaildate.isEmail(email)){
            return false;
        }
        //先删掉历史记录
        LagouAuthCode del = new LagouAuthCode();
        del.setEmail(email);
        lagouAuthCodeService.delete(del);
        long timeMillis = System.currentTimeMillis();
        String code = (timeMillis+"").substring(7);
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        lagouAuthCode.setCreatetime(MyDateTime.getCurrentDateTime());
        lagouAuthCode.setExpiretime(MyDateTime.getAfterTenMinute());
        LagouAuthCode save = lagouAuthCodeService.save(lagouAuthCode);
        if (save.getId() != null){
            //去发邮件将验证码发送到传入的邮箱
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(email);
            message.setSubject("注册账号验证码");
            message.setText(code);
            javaMailSender.send(message);
        }
        return true;
    }
}
